package org.chen.common.task;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 定时任务数据库实体类
 * 表名：scheduled_flight_task
 */
@Data
@TableName("flight_scheduled_flight_task")
public class ScheduledTaskEntity {
    
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private String id;
    
    // 基础信息
    @TableField("name")
    private String name;                    // 任务名称
    
    @TableField("status")
    private String status;                  // 任务状态：ACTIVE, PAUSED, STOPPED
    
    // 航线配置
    @TableField("departure")
    private String departure;               // 出发城市代码
    
    @TableField("destination")
    private String destination;             // 目的地城市代码
    
    @TableField("trip_type")
    private String tripType;                // 行程类型：oneway/roundtrip
    
    @TableField("adults")
    private Integer adults;                 // 成人数量
    
    @TableField("children")
    private Integer children;               // 儿童数量
    
    @TableField("infants")
    private Integer infants;                // 婴儿数量
    
    @TableField("cabin_class")
    private String cabinClass;              // 舱位等级
    
    // 动态日期配置
    @TableField("base_date")
    private LocalDate baseDate;             // 基准开始日期
    
    @TableField("crawl_cycle")
    private Integer crawlCycle;             // 爬取周期（天数）
    
    @TableField("execution_count")
    private Integer executionCount;         // 每次执行的次数
    
    @TableField("is_round_trip")
    private Boolean isRoundTrip;            // 是否往返
    
    @TableField("round_trip_days")
    private Integer roundTripDays;          // 往返行程天数
    
    // 调度配置
    @TableField("cron_expression")
    private String cronExpression;          // Cron表达式
    
    @TableField("export_path")
    private String exportPath;              // 导出路径
    
    @TableField("export_lowest_price_only")
    private Boolean exportLowestPriceOnly;  // 是否只导出最低价格
    
    // 邮件通知配置
    @TableField("email_notification")
    private Boolean emailNotification;      // 是否启用邮件通知
    
    @TableField("email_recipients")
    private String emailRecipients;         // 邮件接收者（JSON数组字符串）
    
    // 执行统计
    @TableField("total_run_count")
    private Integer totalRunCount;          // 总运行次数
    
    @TableField("success_count")
    private Integer successCount;           // 成功次数
    
    @TableField("failed_count")
    private Integer failedCount;            // 失败次数
    
    @TableField("last_run_at")
    private LocalDateTime lastRunAt;        // 最后运行时间
    
    @TableField("next_run_at")
    private LocalDateTime nextRunAt;        // 下次运行时间
    
    @TableField("last_run_result")
    private String lastRunResult;           // 最后运行结果：SUCCESS, FAILED
    
    @TableField("last_error_message")
    private String lastErrorMessage;        // 最后错误信息
    
    @TableField("last_execution_summary")
    private String lastExecutionSummary;    // 最后执行摘要
    
    // 时间戳
    @TableField(value = "created_at", fill = FieldFill.INSERT)
    private LocalDateTime createdAt;        // 创建时间
    
    @TableField(value = "updated_at", fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updatedAt;        // 更新时间
    
    /**
     * 转换为业务模型
     */
    public ScheduledTask toScheduledTask() {
        ScheduledTask task = new ScheduledTask();
        
        // 基础信息
        task.setId(this.id);
        task.setName(this.name);
        task.setStatus(this.status);
        
        // 航线配置
        task.setDeparture(this.departure);
        task.setDestination(this.destination);
        task.setTripType(this.tripType);
        task.setAdults(this.adults);
        task.setChildren(this.children);
        task.setInfants(this.infants);
        task.setCabinClass(this.cabinClass);
        
        // 动态日期配置
        task.setBaseDate(this.baseDate);
        task.setCrawlCycle(this.crawlCycle);
        task.setExecutionCount(this.executionCount);
        task.setRoundTrip(this.isRoundTrip != null ? this.isRoundTrip : false);
        task.setRoundTripDays(this.roundTripDays);
        
        // 调度配置
        task.setCronExpression(this.cronExpression);
        task.setExportPath(this.exportPath);
        task.setExportLowestPriceOnly(this.exportLowestPriceOnly != null ? this.exportLowestPriceOnly : false);
        
        // 邮件配置
        task.setEmailNotification(this.emailNotification != null ? this.emailNotification : false);
        if (this.emailRecipients != null && !this.emailRecipients.isEmpty()) {
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                task.setEmailRecipients(mapper.readValue(this.emailRecipients, 
                    mapper.getTypeFactory().constructCollectionType(java.util.List.class, String.class)));
            } catch (Exception e) {
                task.setEmailRecipients(new java.util.ArrayList<>());
            }
        }
        
        // 执行统计
        task.setTotalRunCount(this.totalRunCount != null ? this.totalRunCount : 0);
        task.setSuccessCount(this.successCount != null ? this.successCount : 0);
        task.setFailedCount(this.failedCount != null ? this.failedCount : 0);
        task.setLastRunAt(this.lastRunAt);
        task.setNextRunAt(this.nextRunAt);
        task.setLastRunResult(this.lastRunResult);
        task.setLastErrorMessage(this.lastErrorMessage);
        task.setLastExecutionSummary(this.lastExecutionSummary);
        task.setCreatedAt(this.createdAt);
        
        return task;
    }
    
    /**
     * 从业务模型创建实体
     */
    public static ScheduledTaskEntity fromScheduledTask(ScheduledTask task) {
        ScheduledTaskEntity entity = new ScheduledTaskEntity();
        
        // 基础信息
        entity.setId(task.getId());
        entity.setName(task.getName());
        entity.setStatus(task.getStatus());
        
        // 航线配置
        entity.setDeparture(task.getDeparture());
        entity.setDestination(task.getDestination());
        entity.setTripType(task.getTripType());
        entity.setAdults(task.getAdults());
        entity.setChildren(task.getChildren());
        entity.setInfants(task.getInfants());
        entity.setCabinClass(task.getCabinClass());
        
        // 动态日期配置
        entity.setBaseDate(task.getBaseDate());
        entity.setCrawlCycle(task.getCrawlCycle());
        entity.setExecutionCount(task.getExecutionCount());
        entity.setIsRoundTrip(task.isRoundTrip());
        entity.setRoundTripDays(task.getRoundTripDays());
        
        // 调度配置
        entity.setCronExpression(task.getCronExpression());
        entity.setExportPath(task.getExportPath());
        entity.setExportLowestPriceOnly(task.isExportLowestPriceOnly());
        
        // 邮件配置
        entity.setEmailNotification(task.isEmailNotification());
        if (task.getEmailRecipients() != null && !task.getEmailRecipients().isEmpty()) {
            try {
                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                entity.setEmailRecipients(mapper.writeValueAsString(task.getEmailRecipients()));
            } catch (Exception e) {
                entity.setEmailRecipients("[]");
            }
        } else {
            entity.setEmailRecipients("[]");
        }
        
        // 执行统计
        entity.setTotalRunCount(task.getTotalRunCount());
        entity.setSuccessCount(task.getSuccessCount());
        entity.setFailedCount(task.getFailedCount());
        entity.setLastRunAt(task.getLastRunAt());
        entity.setNextRunAt(task.getNextRunAt());
        entity.setLastRunResult(task.getLastRunResult());
        entity.setLastErrorMessage(task.getLastErrorMessage());
        entity.setLastExecutionSummary(task.getLastExecutionSummary());
        entity.setCreatedAt(task.getCreatedAt());
        
        return entity;
    }
}
